import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class TestCompletableFuture2 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始执行...");

        List<CompletableFuture<Integer>> completableFutureList = new LinkedList<>();

        for (int i = 0; i < 10; i++) {
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return new Random().nextInt(100);
            });
            completableFutureList.add(completableFuture);
        }

        CompletableFuture<Integer>[] array = completableFutureList.toArray(new CompletableFuture[0]);
        CompletableFuture<Void> all = CompletableFuture.allOf(array);
        all.thenRun(() -> {
            for (CompletableFuture<Integer> future : completableFutureList) {
                try {
                    Integer result = future.get();
                    System.out.println("结果是" + result);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                }

            }
        });

        System.out.println("主线程继续干其他事...");

        // 等待所有异步任务完成
        all.join();
    }


}
